#!/bin/python3
# -*- coding: utf-8 -*-
import argparse
import os
import platform
import random
import socket
import subprocess
import sys
import time
import traceback
from urllib import parse


WALLPAPER_INDEX_CONF = '{home}/.ckp_wallpaper/index.txt'
WALLPAPER_FOLDER_CONF = '{home}/.ckp_wallpaper/wallpaper_folder.conf'


def now():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


def print_short_line(c='*', l=20):
    print(c*l)


def exec_shell(cmd):
    """
    执行 shell 返回 exitstatus
    """
    # print(cmd)
    exitstatus, output = subprocess.getstatusoutput(cmd)
    return exitstatus, output


def read_file(fileFullPath, return_lines=False):
    """
    读取文件，return_lines（=False 返回合并的文本，=True 按行返回数组形式）
    """
    try:
        f = open(fileFullPath, 'r')
        contxtlist = f.readlines()
        f.close()
        # print(contxtlist)
    # except FileNotFoundError as err:
    #     contxtlist = ['FileNotFound']
    # except IOError as err:
    #     contxtlist = ['IOError']
    except Exception as err:
        contxtlist = ['Exception']
    if not return_lines:
        content = ''.join(contxtlist)
        return content
    else:
        return contxtlist


def write_file(fileFullPath, content):
    try:
        with open(fileFullPath, 'w') as f:
            f.write(content)
        return 'success'
    # except FileNotFoundError as err:
    #     return 'FileNotFound: ' + fileFullPath
    # except IOError as err:
    #     return 'IOError: ' + fileFullPath
    except Exception as err:
        return 'Exception'


def get_wallpapers():
    folder = read_file(fileFullPath=WALLPAPER_FOLDER_CONF, return_lines=True)[0].replace('\n', '')
    # print_short_line()
    # print(folder.encode())
    if folder == 'Exception':
        return []
    # if not os.path.isdir(folder):
    #     print('isdir(%s) = False' % folder)
    #     return []
    wallpapers = []
    folder_ex = folder.split('|')
    folder = folder_ex[0]
    WP_EX = ''
    if len(folder_ex) > 1:
        WP_EX = folder_ex[1]
    if folder.endswith("/"):
        folder = folder.rstrip('/')
    print(folder + ' : ' + str(os.path.isdir(folder)))
    if os.path.isdir(folder):
        dest_files = os.listdir(folder)
        for img in dest_files:
            name, ext = os.path.splitext(img)
            fullpath = '%s/%s' % (folder, img)
            # print(fullpath)
            wallpapers.append(fullpath)
    else:
        folder = folder.replace('【', '[').replace('】', ']')
        s, t = exec_shell('/bin/ls %s' % folder)
        # print(t)
        for img in t.split('\n'):
            wallpapers.append(img)
    wp_list = []
    print('WP_EX: ' + WP_EX)
    WP_EX_COUNT = 0
    EXT_EX_COUNT = 0
    for img in wallpapers:
        name, ext = os.path.splitext(img)
        if ext not in ['.jpg', '.png']:
            EXT_EX_COUNT += 1
            continue
        if WP_EX != '':
            WP_EX_IS = False
            for WP_EX_K in WP_EX:
                if WP_EX_K in name:
                    # print(WP_EX_K + ' -> ' + name)
                    WP_EX_COUNT += 1
                    WP_EX_IS = True
                    break
            if WP_EX_IS:
                continue
        wp_list.append(img)
    print('WP_EX_COUNT : ' + str(WP_EX_COUNT))
    print('EXT_EX_COUNT: ' + str(EXT_EX_COUNT))
    print('wallpapers  : ' + str(len((wallpapers))))
    print('wp_list     : ' + str(len((wp_list))))
    return wp_list


def get_wallpaper_index(default=0):
    try:
        idx = int(read_file(fileFullPath=WALLPAPER_INDEX_CONF, return_lines=True)[0])
    except Exception as err:
        print(err)
        idx = default
    print('get_wallpaper_index: %d' % idx)
    return idx


def get_screen():
    """获取当前监视器名称"""
    sts, screen = exec_shell("xrandr|grep '\ connected\ '|grep primary|awk '{print $1}'")
    return screen


def set_wallpaper(screen, img):
    """设置壁纸"""
    exec_shell('dbus-send --dest=com.deepin.daemon.Appearance /com/deepin/daemon/Appearance --print-reply com.deepin.daemon.Appearance.SetMonitorBackground string:"%s" string:"file://%s"' % (screen, img))


def main(isloop=True):
    print(now())
    wps = get_wallpapers()
    print('壁纸图片数量：%d' % len(wps))
    if len(wps) == 0:
        if isloop:
            return 'continue'
        else:
            return 'exit'
    idx = get_wallpaper_index() + 1
    if idx >= len(wps):
        idx = 0
    wallpaper = wps[idx]
    print(wallpaper)
    set_wallpaper(SCREEN_NAME, wallpaper)
    print_short_line('-')
    write_file(WALLPAPER_INDEX_CONF, ('%d\n%s\n%s' % (idx, now(), wallpaper)))
    return ''


if __name__ == '__main__':
    SCREEN_NAME = get_screen()
    # print(SCREEN_NAME)
    parser = argparse.ArgumentParser(description='manual to this script')
    parser.add_argument('--action', type=str, default='')
    args = parser.parse_args()
    print(args.action)
    if args.action == 'next':
        main(isloop=False)
        sys.exit()
    while 1:
        if main() == 'continue':
            empty_wait = 10
            if empty_wait > {sleep}:
                empty_wait = {sleep}
            time.sleep(empty_wait)
            continue
        time.sleep({sleep})
